package com.dxysun.springboot.convert;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import com.dxysun.springboot.advice.MyResponseBodyAdvice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyCustomHttpMessageConverter extends MappingJackson2HttpMessageConverter
{
    private static final Log logger = LogFactory.getLog(MyCustomHttpMessageConverter.class);

    static String key = "";

	@Override
	protected boolean supports(Class clazz)
	{
		// 表明只处理UserEntity类型的参数。
//		return User.class.isAssignableFrom(clazz);
		return true;
	}

	@Override
	protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException
	{
		/*// decrypt
		byte[] bytes = null;
		inputMessage.getBody().read(bytes);
		String json = new String(AESUtil.decrypt(bytes, key));
		JavaType javaType = getJavaType(clazz, null);
		//conversion
		return this.objectMapper.readValue(json, javaType);*/
        logger.info("MyCustomHttpMessageConverter readInternal");
        return super.readInternal(clazz, inputMessage);
	}

	@Override
	protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException
	{
		// Use Jackson's ObjectMapper to convert Java objects into Json String
		/*ObjectMapper mapper = getObjectMapper();
		Map<String ,Object> map = new HashMap<>();
		map.put("code", "ok");
		map.put("msg", "in HttpMessageConverter");
		map.put("result", object);
		String json = mapper.writeValueAsString(map);
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.currentRequestAttributes()).getRequest();
        logger.info("MyCustomHttpMessageConverter writeInternal");
		logger.info("MyCustomHttpMessageConverter outputMessage encryptData:" + request.getHeader("encryptData"));
		logger.info("MyCustomHttpMessageConverter outputMessage isEncrypt:" + request.getParameter("isEncrypt"));

        outputMessage.getBody().write(json.getBytes());*/
		super.writeInternal(object, type, outputMessage);
	}

}
